/**
 * @author CT
 * @email 994599447@qq.com
 * @date 2017.8.14
 */

'use strict';

import React, { Component } from 'react'
import { Image,Dimensions,StyleSheet,FlatList,TouchableNativeFeedback,InteractionManager,Alert, } from 'react-native'
import {
    Container,
    Button,
    Text,
    Header,
    Left,
    Body,
    Right,
    Title,
    Content,
    View,
    Thumbnail,
} from 'native-base'
import * as I18n from '../config/i18n'
import Ionicons from 'react-native-vector-icons/Ionicons'
import Utils from '../common/utils'
import * as config from '../config/appConfig'
import { remindDatas,atTopRemindData } from '../actions/homeActions'
import * as Storage from '../common/storage'

const {height, width} = Dimensions.get('window');
/**
 * 首页
 */
export default class HomePage extends Component {

    constructor(props) {
        super(props);
    
    }

    componentWillMount() {
        this._initData();
    }

    //初始化相关数据
    _initData = () => {
        // 交互管理器在任意交互/动画完成之后，允许安排长期的运行工作. 在所有交互都完成之后安排一个函数来运行。
        InteractionManager.runAfterInteractions(() => {
            const {dispatch} = this.props;
            dispatch(remindDatas());
            dispatch(atTopRemindData());
        });
    }


    _onItemPress = (item,index) => {
        this.props.navigation.navigate('EditRemindPage',item);
    };

    _onItemLongPress = (item,index) => {
        Alert.alert(
            '提醒',
            '删除倒计时：' + item.title + ' ？',
            [
              {text: '取消', style: 'cancel'},
              {text: '确定', onPress: () => {
                Storage.removeForKeyId(config.StorageKey.RemindDate,item.id);
                Utils.showToast('已删除' + item.title,'success');
                //刷新倒计时数据
                this.props.dispatch(remindDatas());
                this.props.dispatch(atTopRemindData());
              }},
            ],
            { cancelable: false }
        );
    }

    //绘制提醒分类图标
    _renderRemindTypeIcon = (type) => {
        let obj = config.RemindType[0];

        for(let i=0;i<config.RemindType.length;i++){
            if(type == config.RemindType[i].id){
                obj = config.RemindType[i];
                break;
            }
        }
        
        return (
            <View style={[styles.itemIcon,styles.center,{backgroundColor:obj.iconColor}]}>
                <Ionicons name={obj.iconName} size={20} color={'white'}/>
            </View>
        );
    }

    //渲染标题栏
    _renderTitleBar = () => {
        return (
            <Header
                androidStatusBarColor="#00797e"
                style={{backgroundColor:'#00adb4'}}>
                <Body>
                    <Title>{I18n.t('app_name')}</Title>
                </Body>
                <Right >
                    <Button transparent light onPress={()=>{this.props.navigation.navigate('AddRemindPage')}}>
                        <Ionicons name = 'md-add' size = {28} color = 'white'/>
                    </Button>
                     <Button transparent light onPress={()=>{this.props.navigation.navigate('SettingsPage')}}>
                        <Ionicons name = 'md-settings' size = {22} color = 'white'/>
                    </Button>
                </Right>
            </Header>
        );
    }

    _renderItem = ({item,index}) => {
        if(Utils.getDateDiff(new Date().toLocaleDateString(),item.date) == 0){
            return (
                <TouchableNativeFeedback onPress={()=>{this._onItemPress(item,index)}} onLongPress={()=>{this._onItemLongPress(item,index)}}>
                    <View style={styles.itemBody}>
                        {this._renderRemindTypeIcon(item.type)}
                        <View style={{flex:1}}>
                            <View style={{flexDirection: 'row'}}>
                                <Text style={{color:'#00adb4'}}>{item.title}</Text>
                            </View>
                            <Text style={styles.itemDate}>{item.date}</Text>
                        </View>
                        <Text style={{color:'#FF3333'}}>{I18n.t('home.remind_item_right_today')}</Text>
                    </View>
                </TouchableNativeFeedback>
            );
        }else if(new Date() < Utils.cnvStringToDate(item.date)){
            return (
                <TouchableNativeFeedback onPress={()=>{this._onItemPress(item,index)}} onLongPress={()=>{this._onItemLongPress(item,index)}}>
                    <View style={styles.itemBody}>
                        {this._renderRemindTypeIcon(item.type)}
                        <View style={{flex:1}}>
                            <View style={{flexDirection: 'row'}}>
                                <Text>{I18n.t('home.remind_distance')}</Text>
                                <Text style={{color:'#00adb4'}}>{item.title}</Text>
                                <Text>{I18n.t('home.remind_surplus')}</Text>
                            </View>
                            <Text style={styles.itemDate}>{item.date}</Text>
                        </View>
                        <Text style={styles.itemRightDat}>{Utils.getDateDiff(new Date().toLocaleDateString(),item.date)}</Text>
                        <Text>{I18n.t('home.remind_day_sub')}</Text>
                    </View>
                </TouchableNativeFeedback>
            );
        }else{
            return (
                <TouchableNativeFeedback onPress={()=>{this._onItemPress(item,index)}} onLongPress={()=>{this._onItemLongPress(item,index)}}>
                    <View style={styles.itemBody}>
                        {this._renderRemindTypeIcon(item.type)}
                        <View style={{flex:1}}>
                            <View style={{flexDirection: 'row'}}>
                                <Text style={{color:'#00adb4'}}>{item.title}</Text>
                                <Text>{I18n.t('home.remind_past')}</Text>
                            </View>
                            <Text style={styles.itemDate}>{item.date}</Text>
                        </View>
                        <Text style={{color:'#ABABAB'}}>{Utils.getDateDiff(new Date().toLocaleDateString(),item.date)}</Text>
                        <Text>{I18n.t('home.remind_day_sub')}</Text>
                    </View>
                </TouchableNativeFeedback>
            );  
        }

    }



    //列表的两端
    _renderListEnd = () => {
        return (
            <View style={{borderWidth:0.5,borderColor:'#D9D9D9'}}/> 
        )
    }

    //列表项分割线
    _renderItemSeparator(){
        return (
            <View style={{borderWidth:0.3,borderColor:'#D9D9D9'}}/> 
        )
    }

    _keyExtractor = (item, index) => item.id;

    render() {
        const {homeReducer} = this.props;
        let { remindDatas,isData,atTopRemindData } = homeReducer;
        return (
            <Container>
                {this._renderTitleBar()}
                <Content>
                    {
                        atTopRemindData!=undefined?(
                            <Image 
                                style={[styles.showBody,styles.center]} 
                                source={require('../images/home_rdbg.jpg')} >
                                <Text style={styles.showHeaderText}>{I18n.t('home.remind_distance')}{atTopRemindData.title}{I18n.t('home.remind_surplus')}</Text>
                                <Text style={styles.showBodyText}>{Utils.getDateDiff(new Date().toLocaleDateString(),atTopRemindData.date)}<Text style={{fontSize: 14,color:'white'}}> {I18n.t('home.remind_day_sub')}</Text></Text>
                                <Text style={styles.showFooterText}>{I18n.t('home.remind_target')}{atTopRemindData.date} {I18n.t('home.remind_week')}{Utils.getWeekDay(atTopRemindData.date)}</Text>
                            </Image>
                        ):(
                            <Image 
                                style={[styles.showBodynNo,styles.center]} 
                                source={require('../images/home_banner.jpg')} >

                            </Image>
                        )
                    }
                    {
                        isData?(
                            <FlatList
                                data={remindDatas}
                                renderItem={this._renderItem.bind(this)}
                                ListHeaderComponent={this._renderListEnd.bind(this)}
                                ItemSeparatorComponent={this._renderItemSeparator.bind(this)}
                                ListFooterComponent={this._renderListEnd.bind(this)}
                                keyExtractor={this._keyExtractor}
                            />
                        ):(
                            <View style={[styles.content,styles.center]}>
                                <Text style={{marginBottom:20,color:'#6c6c6c',fontSize:14,marginTop:30}}>{I18n.t('home.tips')}</Text>
                                <Button block success onPress={()=>{this.props.navigation.navigate('AddRemindPage')}}>
                                    <Text>{I18n.t('home.add')}</Text>
                                </Button>
                            </View>
                        )    
                 }
                </Content>
        
            </Container>
        );
    }

}

const styles = StyleSheet.create({
    center:{
        alignItems: 'center',
        justifyContent: 'center',
    },
    showBody:{
        width: width,
        height: 240,
    },
    showBodynNo:{
        width: width,
        height: 180,
    },
    showHeaderText:{
        fontSize: 20,
        color: 'white',
    },
    showBodyText:{
        fontSize: 60,
        marginTop: 18,
        marginBottom: 20,
        color: 'white',
    },
    showFooterText:{
        fontSize: 16,
        color: 'white',
    },
    itemBody:{
        paddingTop: 10,
        paddingBottom: 10,
        paddingLeft: 15,
        paddingRight: 15,
        flexDirection: 'row',
        backgroundColor: 'white',
        alignItems: 'center',
    },
    itemIcon:{
        width: 30,
        height: 30,
        marginRight: 10,
        borderRadius: 14,
        borderWidth: 0.5,
        borderColor: '#CCC',
    },
    itemDate:{
        fontSize: 13,
        color: '#ABABAB',
    },
    itemRightDat:{
        color:'#00adb4'
    },
    content:{
        padding:10,
        flex:1,
        borderTopWidth:0.5,
        borderTopColor:'#CCC'
    },
  });
  

